package com.rjj.wlqq.jcrop;

import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import java.awt.image.BufferedImage;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @author renjianjun
 * @date 2020/10/23 16:25
 * @email 215060580@qq.com
 */
@Slf4j
@Controller
public class Jcrop {

    @RequestMapping("head")
    public String jcrop() {
        return "/jcrop/headUpload";
    }

    /**
     * 头像上传
     * url:/system/sysAccount/uploadHeaderPic
     * <p>
     * 先把图片上传到服务其上，根据参数进行裁剪，然后把原来的那张图片删除，就可以了。把资源也省下来了
     */
    @ResponseBody
    @RequestMapping(value = "/uploadFile", method = RequestMethod.POST)
    public String uploadHeaderPic(HttpServletRequest request, @RequestParam("img0") MultipartFile uploadFile) {
        //getFiles("head");
        //获得参数
        int left = (int) Math.round(Double.parseDouble(request.getParameter("x11")));
        int top = (int) Math.round(Double.parseDouble(request.getParameter("y11")));
        int width = (int) Math.round(Double.parseDouble(request.getParameter("w")));
        int height = (int) Math.round(Double.parseDouble(request.getParameter("h")));
        String para = request.getParameter("tw");
        String para2 = request.getParameter("ty");
        String substring = para.substring(0, para.length() - 2);
        int tw = (int) Math.round(Double.parseDouble(substring));
        String substring2 = para2.substring(0, para2.length() - 2);
        int ty = (int) Math.round(Double.parseDouble(substring2));

        //UploadFile uploadFile = null;
        //for (UploadFile uploadFile : files) {
        InputStream source = null;
        try {
            source = uploadFile.getInputStream();
        } catch (IOException e) {
            e.printStackTrace();
        }
        String fileName = uploadFile.getOriginalFilename();

        String pathName = getUploadPath() + File.separator + System.currentTimeMillis() + fileName;
        //String name = PathKit.getWebRootPath()+pathName;
        System.out.println(pathName);
        boolean isSave = saveImage(source, pathName, top, left, width, height, tw, ty);


        /** 保存用户和图片的关系*/
      /*  SysAccount account = getLoginAccount();
        //删除原来的图片
        File file = new File(PathKit.getWebRootPath()+account.getAvatar());
        file.delete();
        //跟新新图片地址
        account.setAvatar(pathName);
        account.update();*/

        //删除原来的图片，
        //source.delete();

        JSONObject json = new JSONObject();
        if (isSave) {
            return Json("头像更新成功！");
        } else {
            return Json("头像更新失败！");
        }
    }

    /**
     * 对图片进行剪裁，只保存选中的区域
     *
     * @param img    原图路径
     * @param dest   目标路径
     * @param top
     * @param left
     * @param width
     * @param height
     * @return
     * @throws IOException
     */
    public static boolean saveImage(InputStream img, String dest, int top, int left, int width, int height, int tw, int ty) {
        try {
            File fileDest = new File(dest);
            if (!fileDest.getParentFile().exists())
                fileDest.getParentFile().mkdirs();
            //读取原图
            BufferedImage bfi = (BufferedImage) ImageIO.read(img);
            //获得原图片的大小，并且按照前端页面中设置的图片的大小，缩放宽高
            BufferedImage bi = ImageKit.resize(bfi, tw, ty);

            //下边是裁剪
            height = Math.min(height, bi.getHeight());
            width = Math.min(width, bi.getWidth());
            if (height <= 0) height = bi.getHeight();
            if (width <= 0) width = bi.getWidth();
            top = Math.min(Math.max(0, top), bi.getHeight() - height);
            left = Math.min(Math.max(0, left), bi.getWidth() - width);
            //截取图片，.getSubimage(left（左边位置）, top（上边位置）, width（要截图的宽）, height（要截取图片的高度）);
            BufferedImage bi_cropper = bi.getSubimage(left, top, width, height);

            return ImageIO.write(bi_cropper, "jpeg", fileDest);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return false;
    }

    @ResponseBody
    @ApiOperation("上传附件")
    @RequestMapping(value = "/uploadFile2", method = RequestMethod.POST)
    public String uploadFile(@RequestParam("img0") @ApiParam(value = "二进制文件流") MultipartFile file) {
        String fileName = file.getOriginalFilename();//获取文件名
        fileName = getFileName(fileName);
        String filepath = getUploadPath();
        if (!file.isEmpty()) {
            try (BufferedOutputStream out = new BufferedOutputStream(
                    new FileOutputStream(new File(filepath + File.separator + fileName)))) {
                out.write(file.getBytes());
                out.flush();
                return Json(fileName);
            } catch (FileNotFoundException e) {
                return Json("上传文件失败 FileNotFoundException：" + e.getMessage());
            } catch (IOException e) {
                return Json("上传文件失败 IOException：" + e.getMessage());
            }
        } else {
            return Json("上传文件失败，文件为空");
        }
    }

    /**
     * 文件名后缀前添加一个时间戳
     */
    private String getFileName(String fileName) {
        int index = fileName.lastIndexOf(".");
        final SimpleDateFormat sDateFormate = new SimpleDateFormat("yyyymmddHHmmss");  //设置时间格式
        String nowTimeStr = sDateFormate.format(new Date()); // 当前时间
        fileName = fileName.substring(0, index) + "_" + nowTimeStr + fileName.substring(index);
        return fileName;
    }

    /**
     * 获取当前系统路径
     */
    private String getUploadPath() {
        File path = null;
        try {
            path = new File(ResourceUtils.getURL("classpath:").getPath());
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        if (!path.exists()) path = new File("");
        File upload = new File(path.getAbsolutePath(), "static/upload/");
        if (!upload.exists()) upload.mkdirs();
        return upload.getAbsolutePath();
    }

    public String Json(Object obj) {
        ObjectMapper objectMapper = new ObjectMapper();
        try {
            return objectMapper.writeValueAsString(obj);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        return "";
    }
}
